package com.wzl.demo_08_04;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class MyService extends Service {

    // 创建服务
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("MyService", "onBind");
        //主线程阻塞
        /*for (int i = 0; i < 10; i++) {
            try {
                Log.i("MyService", "onBind" + i);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }*/
        return new MyBinder();
    }
    // 创建Binder
    public class MyBinder extends Binder {
        // 获取服务
        public MyService getService() {
            return MyService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MyService", "onCreate");
        // 开启一个线程,否则主线程阻塞
        /*for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }*/
        new Thread(new MyThread()).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("MyService", "onDestroy");
    }

    // 随机数
    public int nextInt(){
        return (int) (Math.random() * 10);
    }

    public class MyThread implements Runnable {
        @Override
        public void run() {
            Log.i("MyThread", "run");
            for (int i = 0; i < 10; i++) {
                try {
                     Log.i("MyService", "onBind" + i);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
